package zy.blogs.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zy.blogs.entity.Order;
import zy.blogs.entity.ParkingLot;
import zy.blogs.entity.PricingStandard;
import zy.blogs.entity.Vehicle;
import zy.blogs.service.OrderService;
import zy.blogs.service.ParkingLotService;
import zy.blogs.service.PricingStandardService;
import zy.blogs.service.VehicleService;

import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/order")
public class OrderController {
    private final OrderService service;
    private final PricingStandardService pricingStandardService;
    private final ParkingLotService parkingLotService;
    private final VehicleService vehicleService;
    @Autowired
    public OrderController(OrderService service
            ,PricingStandardService pricingStandardService
            ,ParkingLotService parkingLotService
            ,VehicleService vehicleService){
        this.service=service;
        this.pricingStandardService=pricingStandardService;
        this.parkingLotService=parkingLotService;
        this.vehicleService=vehicleService;
    }

    @RequestMapping("/list")
    public String list(Model model){
        List<Order> entities= service.getAll();
        model.addAttribute("list",entities);
        return "/order/list";//此处是对应前端UI的URL
    }

    @RequestMapping(value = "/insert")
    public String insert(Model model){
        // 新建user对象,给到ui的model
        model.addAttribute("order",new Order());
        List<ParkingLot> parkingLots=parkingLotService.getAll();
        model.addAttribute("parkingLots",parkingLots);
        return "/order/edit";
    }

    @RequestMapping(value = "/edit/{id}")
    public String edit(@PathVariable("id")Long id, Model model){
        // 根据id值查找指定的那一行数据
        Order entity=service.getById(id);
        model.addAttribute("order",entity);
        List<ParkingLot> parkingLots=parkingLotService.getAll();
        model.addAttribute("parkingLots",parkingLots);
        return "/order/edit";
    }


    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(@ModelAttribute("order") Order entity
            , @RequestParam("isPayCompleted") boolean isPayCompleted
            , @RequestParam("isRequireInvoicing") boolean isRequireInvoicing
            , @RequestParam("parkingLotId") Long parkingLotId
            , @RequestParam("pricingStandardId") Long pricingStandardId
            , @RequestParam("vehicleId") Long vehicleId) throws Exception {

        entity.setPayComplete(isPayCompleted);
        entity.setRequireInvoicing(isRequireInvoicing);

        ParkingLot parkingLot=parkingLotService.getById(parkingLotId);
        PricingStandard pricingStandard=pricingStandardService.getById(pricingStandardId);
        Vehicle vehicle=vehicleService.getById(vehicleId);

        entity.setParkingLot(parkingLot);
        entity.setPricingStandard(pricingStandard);
        entity.setVehicle(vehicle);

        // order插入实现
        Optional.ofNullable(entity.getId())
                .orElse(entity.getId()==null?service.insert(entity):null);

        //order更新
        Optional.ofNullable(entity.getId())
                .ifPresent(order->{
                    Order od=service.getById(entity.getId());
                    // 获取当前时间作为离场时间
                    od.setOutDateTime(new Date());

                    LocalDateTime in=LocalDateTime.ofInstant(od.getInDateTime().toInstant(), ZoneId.systemDefault());
                    LocalDateTime out=LocalDateTime.ofInstant(od.getOutDateTime().toInstant(), ZoneId.systemDefault());
                    Long durationHour= Duration.between(in,out).toHours();//入场-出场的时间间隔(小时)

                    od.setPayComplete(isPayCompleted);
                    od.setRequireInvoicing(isRequireInvoicing);
                    od.setParkingLot(parkingLot);
                    od.setPricingStandard(pricingStandard);
                    od.setVehicle(vehicle);

                    if(durationHour<24 && durationHour<od.getPricingStandard().getExceedingHours()){
                        od.setPrice(BigDecimal.valueOf(od.getPricingStandard().getHourlyRate()*durationHour));
                    } else {
                        Long durationDay=durationHour/24;
                        durationHour=durationHour%24;
                        od.setPrice(BigDecimal.valueOf(od.getPricingStandard().getDailyRate()*durationDay
                                +od.getPricingStandard().getHourlyRate()*durationHour));

                    }
                    service.update(od);
                });


        return "redirect:/order/list";
    }

    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id")Long id,Model model){
        Order entity=service.getById(id);
        model.addAttribute("order",entity);
        return "/order/detail";
    }

    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id")Long id){
        boolean result=service.delete(service.getById(id));
        return "redirect:/vehicle/list";
    }
}
